import getUserTempId from "@/utils/userTempId";
import { reqLogin, reqUserInfo, reqLogout } from "@/api";
import {
  SET_USERTOKEN_STATE,
  SET_USERINFO_STATE,
  RESET_USER_STATE,
} from "../constant-type";
import { getToken, setToken, removeToken } from "@/utils/token";

const state = {
  userTempId: getUserTempId(),
  token: getToken() || "",
  userInfo: {},
};

const mutations = {
  // 1.修改token
  [SET_USERTOKEN_STATE](state, payload) {
    state.token = payload.token;
    setToken(payload.token);
  },
  // 2.修改userInfo
  [SET_USERINFO_STATE](state, payload) {
    state.userInfo = payload.userInfo;
  },
  // 3.重置token和user数据
  [RESET_USER_STATE](state) {
    state.token = "";
    removeToken();
    state.userInfo = {};
  },
};

const actions = {
  // 获取token
  async getToken({ commit }, payload) {
    try {
      const result = await reqLogin(payload);
      commit(SET_USERTOKEN_STATE, result);
    } catch (err) {
      alert(err.message);
      return Promise.reject();
    }
  },
  // 请求用户信息
  async getUserInfo({ commit }) {
    try {
      let result = await reqUserInfo();
      commit(SET_USERINFO_STATE, { userInfo: result });
    } catch (e) {
      alert(e.message);
      return Promise.reject(err);
    }
  },
  // 3.退出登录
  async getLogout({ commit }) {
    try {
      await reqLogout();
      alert("退出登录成功");
      commit(RESET_USER_STATE);
    } catch (err) {
      alert(err.message);
      return Promise.reject(err);
    }
  },
  // 4.清理user数据
  resetToken({ commit }) {
    commit(RESET_USER_STATE);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
